<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="复习时间" prop="plantime">
        <el-date-picker clearable size="small"
          v-model="queryParams.plantime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择复习时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="复习计划" prop="goovereplan">
        <el-input
          v-model="queryParams.goovereplan"
          placeholder="请输入复习计划"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="复习阶段" prop="planstage">
        <el-input
          v-model="queryParams.planstage"
          placeholder="请输入复习阶段"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="阶段完成时间" prop="stageovertime">
        <el-input
          v-model="queryParams.stageovertime"
          placeholder="请输入阶段完成时间"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否完成" prop="exist">
        <el-input
          v-model="queryParams.exist"
          placeholder="请输入是否完成"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['plan:plan:add']"
        >设定复习计划</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['plan:plan:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['plan:plan:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['plan:plan:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="planList"  :row-class-name="tableRowClassName">
<!--      <el-table-column type="selection" width="55" align="center" />-->
<!--      <el-table-column label="主键" align="center" prop="uid" />-->
      <el-table-column label="学习时间" align="center" prop="plantime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.plantime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="复习数量" align="center" prop="plannumber" />
      <el-table-column label="复习计划" align="center" prop="goovereplan" />
      <el-table-column label="当前复习阶段" align="center" prop="planstage" />
      <el-table-column label="阶段完成时间" align="center" prop="stageovertime" />
      <el-table-column label="是否完成" align="center" prop="exist" />
<!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
<!--        <template slot-scope="scope">-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--            v-hasPermi="['plan:plan:edit']"-->
<!--          >修改</el-button>-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['plan:plan:remove']"-->
<!--          >删除</el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改复习计划存储对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body fullscreen @open="show">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="复习计划" prop="plancontent">
          <el-input v-model="form.plancontent" placeholder="请输入复习计划" />
          <span>创建规则： 注意使用英文"."分隔如 1.2.7 代表录入后第一天、第二天、第七天提醒复习，最多设置15个复习次数,10个复习计划。</span>
        </el-form-item>
        <el-form-item label="提醒内容" prop="context">
          <el-input v-model="form.context" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="邮件提醒" prop="context">
        <el-switch v-model="form.email"> </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">创建复习计划</el-button>
        <el-button type="danger" @click="cancel">关闭</el-button>
      </div>
      <hr/>
      <span>下面是现有的所有复习计划注意：（点击左侧复选框切换设为默认计划，下次计划创建将使用默认计划）【系统会创建艾宾浩斯复习计划，需要你看到这短话刷新一下页面就能看到】</span><br/>
      <hr/>
      <el-table ref="multipleTable"  v-loading="loading" :data="PlancontentList" @select-all="handleSelectionChange3" @select="handleSelectionChange2">
        <el-table-column type="selection" width="55" align="center" />
<!--        <el-table-column label="主键" align="center" prop="uid" />-->
        <el-table-column label="复习计划" align="left" prop="plancontent" >
          <template slot-scope="scope">
            <i class="el-icon-time"></i>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <span>{{scope.row.plancontent}}</span>
          </template>
        </el-table-column>
        <el-table-column label="提醒内容" align="center" prop="context" />
        <el-table-column label="是否发邮件" align="center" prop="email" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
<!--            <el-button-->
<!--              size="mini"-->
<!--              type="text"-->
<!--              icon="el-icon-edit"-->
<!--              @click="handleUpdate2(scope.row)"-->
<!--            >修改</el-button>-->
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete2(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-dialog>
<!--    &lt;!&ndash; 添加或修改复习计划对话框 &ndash;&gt;-->
<!--    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>-->
<!--      <el-form ref="form" :model="form" :rules="rules" label-width="80px">-->
<!--        <el-form-item label="复习时间" prop="plantime">-->
<!--          <el-date-picker clearable size="small"-->
<!--            v-model="form.plantime"-->
<!--            type="date"-->
<!--            value-format="yyyy-MM-dd"-->
<!--            placeholder="选择复习时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="复习计划" prop="goovereplan">-->
<!--          <el-input v-model="form.goovereplan" placeholder="请输入复习计划" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="复习阶段" prop="planstage">-->
<!--          <el-input v-model="form.planstage" placeholder="请输入复习阶段" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="阶段完成时间" prop="stageovertime">-->
<!--          <el-input v-model="form.stageovertime" placeholder="请输入阶段完成时间" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="是否完成" prop="exist">-->
<!--          <el-input v-model="form.exist" placeholder="请输入是否完成" />-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--      <div slot="footer" class="dialog-footer">-->
<!--        <el-button type="primary" @click="submitForm">确 定</el-button>-->
<!--        <el-button @click="cancel">取 消</el-button>-->
<!--      </div>-->
<!--    </el-dialog>-->
  </div>
</template>

<script>
import { listPlan, getPlan, delPlan, addPlan, updatePlan } from "@/api/plan/plan";
import { listPlancontent, getPlancontent, delPlancontent, addPlancontent, updatePlancontent,mainisnothing } from "@/api/Plancontent/Plancontent";


export default {
  name: "Plan",
  data() {
    return {
      // 复习计划存储表格数据
      PlancontentList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: false,
      // 非多个禁用
      multiple: false,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 复习计划表格数据
      planList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        plantime: null,
        goovereplan: null,
        planstage: null,
        stageovertime: null,
        exist: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      start: 0
    };
  },
  created() {
    this.getList();
    this.getList2();
  },
  mounted() {

  },
  methods: {
    tableRowClassName({row, rowIndex}){
      //这里判断是否要复习
      //首先判断 当前阶段是否已经过期 学习时间+复习阶段
      var jd=this.dateChange(row.planstage,row.plantime);
      var date = new Date(jd)<new Date(); //具备复习条件
      if(date){
        return 'success-row';
      }
    },
    dateChange(num,date) {
      if (!date) {
        date = new Date();//没有传入值时,默认是当前日期
        date = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
      }
      date += " 00:00:00";//设置为当天凌晨12点
      date = Date.parse(new Date(date))/1000;//转换为时间戳
      date += (86400) * num;//修改后的时间戳
      var newDate = new Date(parseInt(date) * 1000);//转换为时间
      return newDate.getFullYear() + '-' + (newDate.getMonth() + 1) + '-' + newDate.getDate();
    },
    /** 查询复习计划存储列表 */
    getList2() {
      this.loading = true;
      listPlancontent(this.queryParams).then(response => {
        for(const val of response.rows){
          if(val.email!="true"){
            val.email="不发送";
          }else{
            val.email="发送";
          }
        }
        this.PlancontentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询复习计划列表 */
    getList() {
      this.loading = true;
      listPlan(this.queryParams).then(response => {
        this.planList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        uid: null,
        plantime: null,
        goovereplan: null,
        planstage: null,
        stageovertime: null,
        exist: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange3(selection) {
      this.PlancontentList.forEach(row => {
        if(row.main==="1"){
          this.$refs.multipleTable.clearSelection();
          this.$refs.multipleTable.toggleRowSelection(row, true);
          this.$message({
            message:"只能选择一项复习计划",
            type:'warning'
          })
          return;
        }
      })
    },
    // 多选框选中数据
    handleSelectionChange2(selection) {
      if(selection.length==0){ //用户清空了所有选择
        this.PlancontentList.forEach(row => {
          if(row.main==="1"){
            this.$refs.multipleTable.toggleRowSelection(row, true);
            this.$message({
              message:"至少选择一个复习计划",
              type:'warning'
            })
            return;
          }
        })
      }else{
        var row=selection[selection.length-1];
        this.$refs.multipleTable.clearSelection();

        this.$refs.multipleTable.toggleRowSelection(row,true);
        this.updateselect(row);

      }
      this.ids = selection.map(item => item.uid)
      this.single = selection.length!==1
      this.multiple = !selection.length
      this.start=0;
    },
    //切换默认复习计划
    updateselect(row){
      row.main="1";
      this.PlancontentList.forEach(val => {
        if(val.uid!=row.uid){
          val.main="0"
        }
      });
          mainisnothing().then();
      updatePlancontent(row).then(response => {
        this.$message({
          message:"复习计划切换成功",
          type:'success'
        })
      });
    },
    //Dialog的打开回调
    show() {
      //防抖
      setTimeout(() => {
        this.$nextTick(() => {
          this.PlancontentList.forEach(row => {
            if(row.main==="1"){
              this.$refs.multipleTable.toggleRowSelection(row, true)
            }
          })
        })
      }, 0);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加复习计划";


    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const uid = row.uid || this.ids
      getPlan(uid).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改复习计划";
      });
    },
     isNumber(val){
       var re = /^[0-9]+.?[0-9]*/;//判断字符串是否为数字//判断正整数/[1−9]+[0−9]∗]∗/
       if (!re.test(val)) {
         return false;
       }
       return true;

      },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.uid != null) {
            updatePlan(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList2();
            });
          } else {
            if(this.form.plancontent==null || this.form.context==null){
              this.$message({
                message:"请输入完整的复习内容后在创建",
                type:'warning'
              })
              return;}
            var sp=this.form.plancontent.split(".");
            if(sp.length<1||sp.length>15){
              this.$message.error("复习计划制定错误，请仔细查看规则!");
              return;
            }

            for(const b of sp){
              if(!this.isNumber(b)){
                this.$message.error("计划内包含非数字字符！请仔细查看规则！")
                return;
              }
            }

            for(let i=sp.length-1; i>0; i--){
              for(let x=i-1;x>-1;x--){
                if(parseInt(sp[i])<=parseInt(sp[x])){
                  this.$message.error("复习计划中的数字必须是递增的，后面的天数不可以小于前面的天数，请仔细查看规则!");
                  return;
                }
              }
            }

            //不许重复添加
            for(const val of this.PlancontentList){
              console.log(val)
              if(val.plancontent===this.form.plancontent){
                this.$message.error("已创建此类计划，禁止重复添加！");
                return;
              }
            }


            addPlancontent(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList2();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const uids = row.uid || this.ids;
      this.$modal.confirm('是否确认删除复习计划为"' + row.plancontent + '"的数据项？').then(function() {
        return delPlan(uids);
      }).then(() => {
        this.getList();
        this.getList2();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('plan/plan/export', {
        ...this.queryParams
      }, `plan_${new Date().getTime()}.xlsx`)
    },
    /** 修改按钮操作 */
    handleUpdate2(row) {
      this.reset();
      const uid = row.uid || this.ids
      getPlancontent(uid).then(response => {
        this.form = response.data;
        this.form.email = this.form.email.split(",");
        this.open = true;
        this.title = "修改复习计划存储";
      });
    },
    /** 删除按钮操作 */
    handleDelete2(row) {
      const uids = row.uid || this.ids;
      this.$modal.confirm('是否确认删除复习计划为"' + row.plancontent + '"的数据项？删除前需要保证已经复习完毕或复习内容为0。').then(function() {
        return delPlancontent(uids);
      }).then(() => {
        this.getList2();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>
<style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #d7f8c3;
}
</style>
